package com.ld.security.shop.pay.modules.base.api;

import com.alipay.api.AlipayClient;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.domain.AlipayTradeRefundModel;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.ld.security.common.tomcat.util.RespUtil;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class PayApi {


	@Autowired
	private AlipayClient alipayClient;


	private AlipayTradeWapPayRequest alipayTradeWapPayRequest = new AlipayTradeWapPayRequest();


	private AlipayTradePagePayRequest alipayTradePagePayRequest = new AlipayTradePagePayRequest() ;


	// 电脑网站支付
	@RequestMapping(value="/pay/pc",method = RequestMethod.GET)
	@ApiOperation("电脑网站支付")
	public void pc() throws Exception {

		AlipayTradePagePayModel model =  new AlipayTradePagePayModel();
		model.setOutTradeNo("pay2017" + System.currentTimeMillis());
		model.setTotalAmount("0.01");
		model.setSubject("Iphone6 16G");
		model.setProductCode("FAST_INSTANT_TRADE_PAY");
		alipayTradePagePayRequest.setBizModel(model);

		alipayTradePagePayRequest.setReturnUrl("http://47.106.106.148:8080/swagger-ui.html");
		String form =  alipayClient.pageExecute(alipayTradePagePayRequest).getBody();
		this.write(form);
	}

	// 手机网站支付
	@RequestMapping(value="/pay/wap",method = RequestMethod.GET)
	@ApiOperation("手机网站支付")
	public void wap() throws Exception {

		AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();
		model.setOutTradeNo( "pay2017" + System.currentTimeMillis());
		model.setTotalAmount("0.01");
		model.setSubject("Iphone6 16G");
		model.setProductCode("QUICK_WAP_PAY");
		alipayTradeWapPayRequest.setBizModel(model);

		String form =  alipayClient.pageExecute(alipayTradeWapPayRequest).getBody();
		this.write(form);
	}

	@SneakyThrows
	private void write(String html){

		RespUtil.writeHtml(html);

	}


	@ApiOperation("退款接口")
	@SneakyThrows
	@RequestMapping(value = "/alipayTradeRefund", method = RequestMethod.GET)
	public Object alipayTradeRefundRequest(String outTradeNo) {
		AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
		AlipayTradeRefundModel model = new AlipayTradeRefundModel();
		model.setOutTradeNo(outTradeNo);

		model.setOutRequestNo(outTradeNo);
		model.setRefundReason("测试退款");
		model.setRefundAmount("1");
		request.setBizModel(model);
		AlipayTradeRefundResponse response = alipayClient.execute(request);

		return response;
	}

}
